<template>
  <el-container class="grid-container">
     <el-header class="navbar">
      <div class="navbar-inner">
  <div class="left">
    <el-page-header title=" " class="header">
      <template #icon>
        <el-icon @click="back"><ArrowLeftBold/></el-icon>
      </template>
      <template #content>
        <span class="text">选择网格</span>
      </template>
    </el-page-header>
  </div>
  <div class="right"> <!-- 添加一个 div 用于右对齐菜单 -->
    <el-dropdown trigger="click">
      <span class="el-dropdown-link">
        菜单 <el-icon class="el-icon--right"><arrow-down /></el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="showHistory">查看提交历史</el-dropdown-item>
          <el-dropdown-item @click="showInfo">个人中心</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</div>
    </el-header>
    <el-main class="main">
        <div id="container"></div>
      
    <el-card class="grid-form">
      <el-form :model="reqdata" ref="form" :rules="rules" :hide-required-asterisk="true">
        <el-form-item label="所在省" prop="province">
          <el-select v-model="reqdata.province" placeholder="选择省份" @click="getProvince">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在市" prop="city">
          <el-select v-model="reqdata.city" placeholder="选择城市" @click="getCity" @blur="getMap">
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="reqdata.address" placeholder="请输入具体地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="grid-button" @click="submitForm">下一步</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import axios from '@/utils/axiosUtils';
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeftBold} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import AMapLoader from '@amap/amap-jsapi-loader';

let router = useRouter()
let map = null;
let polygons = [];

let back = function(){
	sessionStorage.removeItem('token');
	sessionStorage.removeItem('isLogin')
	router.push({path:"/"})
}
let reqdata = reactive({
  province: '',
  city: '',
  address: ''
});
let provinceList = reactive([])
let cityList =reactive([])


let rules = reactive({
  province: [{ 
    required: true, 
    trigger: 'change', 
    message: '请选择所在省' 
  }],
  city: [{ 
    required: true, 
    trigger: 'change', 
    message: '请选择所在市' 
  }],
  address: [{ 
    required: true, 
    trigger: 'blur', 
    message: '请填写详细地址' 
  }]
});

let getCity = function(){
	axios.get(
		"http://localhost:7000/service-neps/supervisor/queryCity",
		{
			params : {id : reqdata.province}
		}
	).then(res=>{cityList.splice(0, cityList.length, ...res.data); // 更新 cityList
	console.log(cityList);})
  //  // 调用更新地图函数
  // updateMapCenter(reqdata.city);
}
let getProvince = function(){
	axios.get("http://localhost:7000/service-neps/supervisor/queryProvince",).then(res=>{provinceList.splice(0, provinceList.length, ...res.data); // 更新 provinceList
	console.log(provinceList);})
}
let getMap = function(){
  axios.get("http://localhost:7000/service-neps/supervisor/getCity",{params:{id:reqdata.city}}).then(res=>{
    console.log(res.data);
    updateMapCenter(res.data);
  })
}
let form = ref(null)
let submitForm = function() {
  form.value.validate((valid)=>{
    if(valid){
      router.push({
        path: '/selectAqi',
        query: {
          province: reqdata.province,
          city: reqdata.city,
          address: reqdata.address
		}
	});
    }
    else{
      ElMessage.error("提交失败")
      return false
    }
  })
};
let showHistory = function(){
	router.push({path:'/feedbackList'})
}

let showInfo = function(){
  router.push({path:'/information'})
}

// 初始化地图
onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: '6826d24adcfbdb2039c9927d56f8b5ae',
  };
  AMapLoader.load({
    key: 'f3fb41bf354e429baac3ad4de81cfb26',
    version: '2.0',
    plugins: ['AMap.Scale'],
  })
    .then((AMap) => {
      map = new AMap.Map('container', {
        viewMode: '2D',
        zoom: 11,
        center: [116.397428, 39.90923],
      });
    })
    .catch((e) => {
      console.log(e);
    });
});

onUnmounted(() => {
  map?.destroy();
});

let clearPolygons = function() {
  if (polygons.length > 0) {
    for (let polygon of polygons) {
      polygon.setMap(null); // 清除地图上的多边形
    }
    polygons = []; // 清空多边形数组
  }
};

// 更新地图中心点
let updateMapCenter = function (cityName) {
  if (map) {
   clearPolygons();

    AMap.plugin('AMap.DistrictSearch', function () {
      var district = new AMap.DistrictSearch({
        extensions: 'all',
        level: 'city',
      });
      district.search(cityName, function (status, result) {
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0; i < bounds.length; i++) {
            var polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.7,
              fillColor: '#CCF3FF',
              strokeColor: '#CC66CC',
            });
            polygons.push(polygon);
          }
          map.setFitView();
        }
      });
    });
  }
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 400px;
}

.grid-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('@/assets/kongjing2.jpg') no-repeat center center;
  background-size: cover;
}
.header{
	display: flex;
}
.button{
	margin-left: 100px;
}
.historyButton{
	background:#99b1c4
}
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(to right, #96afc5, #96afc3); /* 使用渐变色 */
  color: white;
  padding: 10px;
  width: 100%;
}

.navbar-inner {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  display: flex;
  align-items: center;
  margin-right: 10px;
  color: black;
}

.main{
  display: flex;
  flex-direction: column; /* 将主轴方向改为垂直排列 */
  /* justify-content: space-between; */
  align-items: center;
   margin-top: 0; /* 确保顶部间距为0 */
  margin-bottom: 0; /* 确保底部间距为0 */
}

.container-main{
  width: 100%;
  height: 400px;
  padding: 0 !important;
}
.grid-form {
  width: 67vw;
  max-width: 400px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  margin-top: 40px;
}

.el-form-item {
  margin-bottom: 30px; /* 增加表单项之间的间距 */
}

.grid-button {
  width: 100%;
  height: 40px;
  font-size: 17px;
  background: linear-gradient(to right, #b79b51, #103428);
  border-color: transparent;
  letter-spacing: 5px; /* 添加字母间距 */
}

.grid-button:hover {
  background: linear-gradient(to right, #ba9632, #0a3426);
}
</style>
